<?php
/**
 * Prado Portal.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: PortalUtil.php 467 2011-01-25 17:24:30Z steen.rabol $
 * @package Pradoportal.Common
 *
 */

/**
 *
 * @package Pradoportal.Common
 */

Prado::using('System.Util.TVarDumper');

class PortalUtil
{
	public static function fatalError($msg, $debug = false)
	{
		if($debug)
		{
			echo '<h1>Fatal Error</h1>';
			if(is_array($msg))
			{
				echo "<pre>";
				print_r($msg);
				echo "</pre>";
			}
			else
			{
				echo '<p>'.$msg.'</p>';
			}

			if(!function_exists('debug_backtrace'))
			{
				return;
			}
			echo '<h2>Debug Backtrace</h2>';
			echo '<pre>';
			$index=-1;
			foreach(debug_backtrace() as $t)
			{
				$index++;
				if($index==0)  // hide the backtrace of this function
					continue;
				echo '#'.$index.' ';
				if(isset($t['file']))
					echo basename($t['file']) . ':' . $t['line'];
				else
					echo '<PHP inner-code>';
				echo ' -- ';
				if(isset($t['class']))
					echo $t['class'] . $t['type'];
				echo $t['function'] . '(';
				if(isset($t['args']) && sizeof($t['args']) > 0)
				{
					$count=0;
					foreach($t['args'] as $item)
					{
						if(is_string($item))
						{
							$str=htmlentities(str_replace("\r\n", "", $item), ENT_QUOTES);
							if (strlen($item) > 70)
								echo "'". substr($str, 0, 70) . "...'";
							else
								echo "'" . $str . "'";
						}
						else if (is_int($item) || is_float($item))
							echo $item;
						else if (is_object($item))
							echo get_class($item);
						else if (is_array($item))
							echo 'array(' . count($item) . ')';
						else if (is_bool($item))
							echo $item ? 'true' : 'false';
						else if ($item === null)
							echo 'NULL';
						else if (is_resource($item))
							echo get_resource_type($item);
						$count++;
						if (count($t['args']) > $count)
							echo ', ';
					}
				}
				echo ")\n";
			}
			echo '</pre>';
			exit(1);
		}
		else
		{
			echo '<h1>Fatal Error</h1>';
			if(is_array($msg))
			{
				foreach($msg as $m)
				{
					echo '<p>'.$m.'</p>';
				}
			}
			else if(is_object($msg))
			{
				var_dump($msg);
			}
			else
			{
				echo '<p>' . $msg . '<p>';
			}
		}

		exit(0);
	}
	/**
	 * @parm $portletname is the name to check if is installed
	 */
	public static function IsPortletInstalled($portletname)
	{
		$application	= Prado::getApplication();
		$db				= $application->DataAccess;
		$portletid		= $db->createCommand("select id from tblportlets where name='$portletname'")->queryScalar();
		return TPropertyValue::ensureBoolean($portletid);
	}

	public static function getAvailablePortalLayouts()
	{
		$application	= Prado::getApplication();
		$basePath		= $application->PortalBasePath . "/protected/Layouts/Portal/" . $application->Parameters['ThemeName'];
		$layouts		= array();

		if(!is_dir($basePath))
		{
			$this->reportError(1,"Could not find layout directory $basePath");
		}

		$folder = @opendir($basePath);
		while($file = @readdir($folder))
		{
			if($file!=='.' && $file!=='..' && $file!=='.svn' && !is_dir($basePath.'/'.$file))
			{
				$path_parts = pathinfo($file);
				if($path_parts['extension'] == "php")
				{

					$clsName = basename($path_parts['basename'],".php");

					if(!class_exists($clsName,false))
					{
						$clsPath = 'Application.Layouts.Portal.' . $application->Parameters['ThemeName'] . '.' . $clsName;
						Prado::using($clsPath);
					}
					$obj = new $clsName();
					if($obj->Type == 1)
					{
						$layouts[] = array("id" => $clsName,"name" =>$obj->Name);
					}
				}
			}
		}
		closedir($folder);
		return $layouts;
	}

	public static function getAvailableAdminThemes()
	{
		$application	= Prado::getApplication();
		$basePath		= $application->PortalBasePath . "/themes/Admin/";
		$themes			= array();

		if(!is_dir($basePath))
		{
			$this->reportError(1,"Could not find theme directory $basePath");
		}

		$folder = @opendir($basePath);
		while($dir = @readdir($folder))
		{
			if($dir !== '.' && $dir !== '..' && $dir !== '.svn' && is_dir($basePath.'/'.$dir))
			{
				$themes[] = $dir;
			}
		}

		closedir($folder);
		return $themes;
	}

	public static function getAvailablePortalThemes()
	{
		$application	= Prado::getApplication();
		$basePath		= $application->PortalBasePath . "/themes/Portal/";
		$themes			= array();

		if(!is_dir($basePath))
		{
			$this->reportError(1,"Could not find theme directory $basePath");
		}

		$folder = @opendir($basePath);
		while($dir = @readdir($folder))
		{
			if($dir !== '.' && $dir !== '..' && $dir !== '.svn' && is_dir($basePath.'/'.$dir))
			{
				$themes[] = $dir;
			}
		}
		closedir($folder);
		return $themes;
	}

	public static function return_bytes($val)
	{
		$val = trim($val);
		$last = strtolower($val{strlen($val)-1});
		switch($last)
		{
			// The 'G' modifier is available since PHP 5.1.0
			case 'g':
				$val *= 1024;
			case 'm':
				$val *= 1024;
			case 'k':
				$val *= 1024;
		}

		return $val;
	}

	public static function return_letter_size($fsize)
	{
		$retval = "";
		// Format size:
		if ($fsize > ((1024 * 1024) * 1024))
		{
			$retval = number_format(((($fsize / 1024) / 1024) / 1024), 2) . ' GB';
		}
		elseif($fsize > (1024 * 1024))
		{
			$retval = number_format((($fsize / 1024) / 1024), 2) . ' MB';
		}
		elseif ($fsize > 1000)
		{
			$retval = number_format(($fsize/1024), 2) . ' KB';
		}
		else
		{
			$retval = $fsize . ' Bytes';
		}

		return $retval;
	}

	public static function isUTF8($str)
	{
		if ($str === mb_convert_encoding(mb_convert_encoding($str, "UTF-32", "UTF-8"), "UTF-8", "UTF-32"))
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	public static function getCookie($cookiename, $default_value = null)
	{
		$ret_val = $default_value;
		$application	= Prado::getApplication();

		foreach($application->Request->Cookies as $cookie)
		{
			if($cookie->Name == $cookiename)
			{
				return $cookie;
			}
		}

		return $ret_val;
	}

	public static function getCookieValue($cookiename, $default_value = null)
	{
		$ret_val		= $default_value;
		$application	= Prado::getApplication();

		foreach($application->Request->Cookies as $cookie)
		{
			if($cookie->Name == $cookiename)
			{
				return $cookie->Value;
			}
		}

		return $ret_val;
	}

	public static function Log($msg)
	{
		PortalUtil::LogAlert($msg);
	}

	public static function LogAlert($msg,$level = TLogger::ALERT)
	{
		Prado::log(TVarDumper::dump($msg),$level);
	}

	public static function Info($msg)
	{
		Prado::trace(TVarDumper::dump($msg));
	}

	public static function Debug($msg)
	{
		Prado::using('Application.Common.3rdParty.dBug');
		new dBug($msg);
	}

	/**
	 * @return Return a array with all system pages
	 */
	public static function getAvailableSystemPages()
	{
		$application	= Prado::getApplication();
		$basePath		= $application->BasePath . "/Pages/System";
		$layouts 		= array();

		if(!is_dir($basePath))
			$this->reportError(1,"Could not find layout directory $basePath");

		$folder = @opendir($basePath);
		while($file = @readdir($folder))
		{
			if($file!=='.' && $file!=='..' && $file!=='.svn' && !is_dir($basePath.'/'.$file))
			{
				$path_parts = pathinfo($file);
				if($path_parts['extension'] == "php")
				{

					$layouts[] = array("name" => "System." . basename($path_parts['basename'],".php"));
				}
			}
		}
		closedir($folder);
		return $layouts;
	}

	public static function getAvailableAdminPages()
	{
		$application	= Prado::getApplication();
		$basePath		= $application->BasePath . "/Pages/Admin";
		$layouts 		= array();

		if(!is_dir($basePath))
			$this->reportError(1,"Could not find layout directory $basePath");

		$folder = @opendir($basePath);
		while($file = @readdir($folder))
		{
			if($file!=='.' && $file!=='..' && $file!=='.svn' && !is_dir($basePath.'/'.$file))
			{
				$path_parts = pathinfo($file);
				if($path_parts['extension'] == "php")
				{
					$layouts[] = array("name" => "Admin." . basename($path_parts['basename'],".php"));
				}
			}
		}
		closedir($folder);
		return $layouts;
	}

	public static function AvailablePagesInPath($path)
	{
		$application	= Prado::getApplication();
		$basePath		= $application->BasePath . "/Pages/$path";
		$layouts 		= array();

		if(!is_dir($basePath))
		{
			return $layouts;
		}
		$folder = @opendir($basePath);
		while($file = @readdir($folder))
		{
			if($file!=='.' && $file!=='..' && $file!=='.svn' && !is_dir($basePath.'/'.$file))
			{
				$path_parts = pathinfo($file);
				if($path_parts['extension'] == "php")
				{
					$layouts[] = array("name" => "$path." . basename($path_parts['basename'],".php"));
				}
			}
		}
		closedir($folder);
		return $layouts;
	}

	public static function getFilesInPath($path, $arrayprefix = null)
	{
		$application	= Prado::getApplication();
		$files	 		= array();

		if(!is_dir($path))
		{
			return false;
		}

		$folder = @opendir($path);
		while($file = @readdir($folder))
		{
			if($file!=='.' && $file!=='..' && $file!=='.svn' && !is_dir($path.'/'.$file))
			{
				if($arrayprefix === null)
				{
					$files[] = $file;
				}
				else
				{
					$files[] = array($arrayprefix => $file);
				}
			}
		}
		closedir($folder);
		return $files;
	}

	public static function GetCssClassesInPortlet($p_portlet)
	{
		$pCss			= null;
		$application	= Prado::getApplication();
		$p_file			= $application->BasePath . "/Portlets/" . $p_portlet . "/Common/" . $p_portlet ."Common.php";
		$p_class		= $p_portlet . 'Common';
		if(!class_exists($p_portlet.'Common',false))
		{
			Prado::using('Application.Portlets.' . $p_portlet . '.Common.' . $p_portlet . 'Common');
		}

		return call_user_func($p_class . '::GetCssClasses');

	}

	public static function GetCssClassesInAllPortlets()
	{
		$application	= Prado::getApplication();
		$db				= $application->DataAccess;
		$pDr			= $db->createCommand("select name from tblportlets")->query();
		$pCss			= array();

		if($pDr)
		{
			foreach($pDr as $p)
			{
				$p_portlet	= $p['name'];
				$pres	= PortalUtil::GetCssClassesInPortlet($p_portlet);
				if($pres !== null)
				{
					$pCss = array_merge($pCss,$pres);
				}
			}
		}

		return $pCss;
	}

	public static function CreateDirStructure($p_path)
	{
		if(is_dir($p_path) || $p_path == '' )
		{
			return;
		}

		try
		{
			return mkdir($p_path,0777,true);
		}
		catch (Exception $e)
		{
			throw new PortalException(1,sprintf("code %d msg: %s dir: %s",$e->getErrorCode(),$e->getErrorMessage(),$p_path));
		}
	}

	public static function xCreateDirStructure($p_path)
	{
	    if (!file_exists($p_path))
		{
	        $_open_basedir_ini = ini_get('open_basedir');

	        if (DIRECTORY_SEPARATOR=='/')
			{
	            /* unix-style paths */
	            $_dir = $p_path;
	            $_dir_parts = preg_split('!/+!', $_dir, -1, PREG_SPLIT_NO_EMPTY);
	            $_new_dir = ($_dir{0}=='/') ? '/' : getcwd().'/';

	            if($_use_open_basedir = !empty($_open_basedir_ini))
				{
	                $_open_basedirs = explode(':', $_open_basedir_ini);
	            }
	        }
			else
			{
	            /* other-style paths */
	            $_dir = str_replace('\\','/', $p_path);
	            $_dir_parts = preg_split('!/+!', $_dir, -1, PREG_SPLIT_NO_EMPTY);
	            if (preg_match('!^((//)|([a-zA-Z]:/))!', $_dir, $_root_dir))
				{
	                /* leading "//" for network volume, or "[letter]:/" for full path */
	                $_new_dir = $_root_dir[1];
	                /* remove drive-letter from _dir_parts */
	                if (isset($_root_dir[3])) array_shift($_dir_parts);
	            }
				else
				{
	                $_new_dir = str_replace('\\', '/', getcwd()).'/';
	            }

	            if($_use_open_basedir = !empty($_open_basedir_ini))
				{
	                $_open_basedirs = explode(';', str_replace('\\', '/', $_open_basedir_ini));
	            }
	        }

	        /* all paths use "/" only from here */
	        foreach ($_dir_parts as $_dir_part)
			{
	            $_new_dir .= $_dir_part;

	            if ($_use_open_basedir)
				{
	                // do not attempt to test or make directories outside of open_basedir
	                $_make_new_dir = false;
	                foreach ($_open_basedirs as $_open_basedir)
					{
	                    if (substr($_new_dir, 0, strlen($_open_basedir)) == $_open_basedir)
						{
	                        $_make_new_dir = true;
	                        break;
	                    }
	                }
	            }
				else
				{
	                $_make_new_dir = true;
	            }

	            if ($_make_new_dir && !file_exists($_new_dir) && !@mkdir($_new_dir) && !is_dir($_new_dir))
				{
	               trigger_error("problem creating directory '" . $_new_dir . "'");
	                return false;
	            }
	            $_new_dir .= '/';
	        }
	    }
	}

	public static function LicensInformation()
	{
		$licinfo = array();
		$licinfo['PRODUCT']				= 'Prado Portal';
		$licinfo['LICTYPE']				= 'Open Source';
		$licinfo['CUSTNAME']			= 'Get Your own Open Source licens';
		$licinfo['CUSTCONTACTNAME']		= 'Open source is free, but donations are welcome.';
		$licinfo['CUSTCONTACTEMAIL']	= 'licens[at]pradoportal.dk';

		$licfile = Prado::getPathOfNamespace('Application.Data') . '/' . 'licens.dat';

		if(file_exists($licfile))
		{
			try
			{
				Prado::using('Application.Common.PortalLicens');
				$pl 	= new PortalLicens();
				$vinfo 	= $pl->validate(file_get_contents($licfile));

				if($vinfo['RESULT'] == 'OK')
				{
					if($vinfo['DATA']['PRODUCT'] === 'pradoportal' && $vinfo['DATA']['LICTYPE'] === 'opensource' && $vinfo['DATA']['CUSTCONTACTEMAIL'] === 'info@pradoportal.dk')
					{
						$licinfo['PRODUCT']				= 'Prado Portal';
						$licinfo['LICTYPE']				= 'Open Source';
						$licinfo['CUSTNAME']			= 'Get Your own Open Source licens';
						$licinfo['CUSTCONTACTNAME']		= 'Open source is free, but donations are welcome.';
						$licinfo['CUSTCONTACTEMAIL']	= 'licens[at]pradoportal.dk';
					}
					else
					{
						$licinfo = $vinfo['DATA'];
						$licinfo['PRODUCT']	= ($vinfo['DATA']['PRODUCT'] === 'pradoportal' ? 'Prado Portal': $vinfo['DATA']['PRODUCT']);
						$licinfo['LICTYPE'] = ($vinfo['DATA']['LICTYPE'] === 'opensource' ? 'Open Source' : $vinfo['DATA']['LICTYPE']);
					}
				}
			}
			catch(Exception $e)
			{
				$licinfo['PRODUCT']				= 'Prado Portal';
				$licinfo['LICTYPE']				= 'Open Source';
				$licinfo['CUSTNAME']			= 'Get Your own Open Source licens';
				$licinfo['CUSTCONTACTNAME']		= 'Open source is free, but donations are welcome.';
				$licinfo['CUSTCONTACTEMAIL']	= 'licens[at]pradoportal.dk';
			}
		}

		return $licinfo;
	}

	public static function LicenseType()
	{
		$licinfo = self::LicensInformation();
		return $licinfo['LICTYPE'];
	}

	public static function DeleteDirStructure($dir,$p_deldir = false)
	{
		$current_dir = @opendir($dir);
		while($entryname = readdir($current_dir))
		{
			if(is_dir("$dir/$entryname") and ($entryname != "." and $entryname!=".."))
			{
				PortalUtil::DeleteDirStructure("${dir}/${entryname}",true);
			}
			elseif($entryname != "." and $entryname!="..")
			{
				@unlink("${dir}/${entryname}");
			}
		}

		@closedir($current_dir);

		if($p_deldir)
		{
			@rmdir($dir);
		}
	}

	public static function MakePassword()
	{
		$makepass	= "";
		$salt		= "abchefghjkmnpqrstuvwxyz0123456789";
		srand((double)microtime()*1000000);
		$i = 0;
		while ($i <= 7)
		{
			$num = rand() % 33;
			$tmp = substr($salt, $num, 1);
			$makepass = $makepass . $tmp;
			$i++;
		}
		return ($makepass);
	}

	public static function getIP()
	{
		// Find the user's IP address. (but don't let it give you 'unknown'!)
		if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_CLIENT_IP']) && (preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['HTTP_CLIENT_IP']) == 0 || preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['REMOTE_ADDR']) != 0))
		{
			// We have both forwarded for AND client IP... check the first forwarded for as the block - only switch if it's better that way.
			if (strtok($_SERVER['HTTP_X_FORWARDED_FOR'], '.') != strtok($_SERVER['HTTP_CLIENT_IP'], '.') && '.' . strtok($_SERVER['HTTP_X_FORWARDED_FOR'], '.') == strrchr($_SERVER['HTTP_CLIENT_IP'], '.') && (preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['HTTP_X_FORWARDED_FOR']) == 0 || preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['REMOTE_ADDR']) != 0))
				$_SERVER['REMOTE_ADDR'] = implode('.', array_reverse(explode('.', $_SERVER['HTTP_CLIENT_IP'])));
			else
				$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CLIENT_IP'];
		}
		if (!empty($_SERVER['HTTP_CLIENT_IP']) && (preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['HTTP_CLIENT_IP']) == 0 || preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['REMOTE_ADDR']) != 0))
		{
			// Since they are in different blocks, it's probably reversed.
			if (strtok($_SERVER['REMOTE_ADDR'], '.') != strtok($_SERVER['HTTP_CLIENT_IP'], '.'))
				$_SERVER['REMOTE_ADDR'] = implode('.', array_reverse(explode('.', $_SERVER['HTTP_CLIENT_IP'])));
			else
				$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CLIENT_IP'];
		}
		elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
		{
			// If there are commas, get the last one.. probably.
			if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false)
			{
				$ips = array_reverse(explode(', ', $_SERVER['HTTP_X_FORWARDED_FOR']));

				// Go through each IP...
				foreach ($ips as $i => $ip)
				{
					// Make sure it's in a valid range...
					if (preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $ip) != 0 && preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['REMOTE_ADDR']) == 0)
						continue;

					// Otherwise, we've got an IP!
					$_SERVER['REMOTE_ADDR'] = trim($ip);
					break;
				}
			}
			// Otherwise just use the only one.
			elseif (preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['HTTP_X_FORWARDED_FOR']) == 0 || preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['REMOTE_ADDR']) != 0)
				$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
		}
		elseif (!isset($_SERVER['REMOTE_ADDR']))
			$_SERVER['REMOTE_ADDR'] = '';
	}

	public static function getGUID()
	{
		// The field names refer to RFC 4122 section 4.1.2
		return sprintf(/*'%04x%04x-%04x-%03x4-%04x-%04x%04x%04x'*/ '%04x%04x-%04x-4%03x-%04x-%04x%04x%04x',
				        mt_rand(0, 65535), mt_rand(0, 65535), // 32 bits for "time_low"
				        mt_rand(0, 65535), // 16 bits for "time_mid"
				        mt_rand(0, 4095),  // 12 bits before the 0100 of (version) 4 for "time_hi_and_version"
				        bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
	            		// 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
    	        		// (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
        	    		// 8 bits for "clk_seq_low"
	    			    mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535) // 48 bits for "node"
    				);
	}

	public static function getPagesAsUrl()
	{
		$app		= Prado::getApplication();
		$db			= $app->DataAccess;
		$service	= $app->Service;
		$p_name	= array();
		$p_url	= array();

		$pages	= $db->createCommand("select fullpath from tblpages")->query()->readAll();
		if($pages && is_array($pages) && count($pages) > 0)
		{
			foreach($pages as $page)
			{
				$p_name[]	= "{" . $page['fullpath'] . "}";
				$p_url[]	= $service->constructUrl($page['fullpath']);
			}
		}
		return array($p_name,$p_url);
	}

	public static function getMemoryUsage($real = true)
	{
		return (memory_get_peak_usage($real) / 1024) . " kb";
	}

	public static function GenId($seqname='ppseq', $startID=1)
	{
		$db	= Prado::getApplication()->DbConnection;
		if($db)
		{
			try
			{
				$getnext	= sprintf("update %s set id=id+1;", $seqname);
				$result		= $db->createCommand($getnext)->execute();
				return $db->createCommand("select id from $seqname")->queryScalar();
			}
			catch(Exception $e)
			{
				$db->createCommand(sprintf("drop table if exists %s",$seqname))->execute();
				$db->createCommand(sprintf("create table %s (id int not null)",$seqname))->execute();
				$db->createCommand(sprintf("insert into %s values (%d)",$seqname, $startID-1))->execute();
				return PortalUtil::GenID($seqname,$startID);
			}
		}
		else
		{
			PortalUtil::fatalError("Faild to connect to the database");
		}
	}

	public static function CreateSequence($seqname='adodbseq',$startID=1)
	{
		$db	= Prado::getApplication()->DbConnection;
		if($db)
		{
			try
			{
				$db->createCommand(sprintf("create table %s (id int not null)",$seqname))->execute();
			}
			catch(Exception $e)
			{
				PortalUtil::fatalError("Db error: " . $e->getMessage());
			}
		}
		else
		{
			PortalUtil::fatalError("Faild to connect to the database");
		}
	}

	public static function DropSequence($seqname='adodbseq')
	{
		$db	= Prado::getApplication()->DbConnection;
		if($db)
		{
			try
			{
				$db->createCommand(sprintf("drop table if exists %s",$seqname))->execute();
			}
			catch(Exception $e)
			{
				PortalUtil::fatalError("Db error: " . $e->getMessage());
			}
		}
		else
		{
			PortalUtil::fatalError("Faild to connect to the database");
		}
	}

	public static function PathName($p_path, $p_createdir = false)
	{
		$retval = "";
		$retval = str_replace('\\','/',$p_path);
		if(substr($retval,-1) != '/')
		{
			$retval .= '/';
		}
		// Remove double //
		$retval = str_replace('//','/',$retval);

		if($p_createdir)
		{
			@mkdir($p_path,0777,true);
		}
		return $retval;
	}

	public static function DbTableExists($tblname)
	{
		$db			= Prado::getApplication()->DbConnection;
		$sql		= "show tables like '$tblname'";
		$dbresult	= $db->createCommand($sql)->query();

		if($dbresult === null)
		{
			$retval = false;
		}
		else
		{
			$retval = true;
		}

		return $retval;
	}

	public static function CreateLangString($string, $key = 'APPLICATION')
	{
		if($string === "" || empty($string))
		{
			return;
		}
		
		Prado::using('Application.Common.Data.PortalLanguageRecord');
		Prado::using('Application.Common.Data.PortalLanguageStringRecord');

		// Get Active languages
		$actLang	= PortalLanguageRecord::finder()->findAll("active =?",1);

		if($actLang !== 0 && is_array($actLang) && count($actLang) > 0)
		{
			foreach($actLang as $aLang)
			{
				$lsRec = PortalLanguageStringRecord::finder()->findByculture_AND_fromvalue($aLang->culture,$string);
				if($lsRec === null)
				{
					$lsRec				= new PortalLanguageStringRecord();
					$lsRec->culture		= $aLang->culture;
					$lsRec->lkey		= 'APPLICATION';
					$lsRec->fromvalue	= $string;
					$lsRec->tovalue		= $string;
					$lsRec->save();	
				}
			}
		}
	}

	public static function request_uri()
	{
		$uri	= "";
		if (isset($_SERVER['REQUEST_URI']))
		{
			$uri = $_SERVER['REQUEST_URI'];
		}
		else
		{
			if (isset($_SERVER['argv']))
			{
				$uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['argv'][0];
			}
			elseif (isset($_SERVER['QUERY_STRING']))
			{
				$uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
			}
			else
			{
				$uri = $_SERVER['SCRIPT_NAME'];
			}
		}

		return $uri;
	}
}
?>